<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片 -->
        <el-card>
          <el-row :gutter="20">
              <el-col :span="8">
                <el-input placeholder="请输入内容" class="input-with-select" v-model="queryObj.query" clearable @clear='getUserList'>
                    <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                </el-input>                 
              </el-col>
              <el-col :span="4">
                  <el-button type="primary" @click="addUser">添加用户</el-button>
              </el-col>
          </el-row>
           <!-- 表格 -->
            <el-table :data="userList" border style="width: 100%" stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="username" label="姓名" ></el-table-column>
                <el-table-column prop="email" label="邮箱" ></el-table-column>
                <el-table-column prop="mobile" label="电话" ></el-table-column>
                <el-table-column prop="role_name" label="角色" ></el-table-column>
                <el-table-column prop="" label="状态" >
                    <template slot-scope="scope">
                       <el-switch v-model="scope.row.mg_state" @change="userState(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column prop="" label="操作" width="180">
                    <template slot-scope="scope">
                        <!-- 修改按钮 -->
                       <el-button type="primary" icon="el-icon-edit" size="mini" @click="revUser(scope.row)"></el-button>
                       <!-- 删除按钮 -->
                       <el-button type="danger" icon="el-icon-delete" size="mini" @click="delUser(scope.row.id)"></el-button>
                       <!-- 分配角色按钮 -->
                       <el-tooltip effect="dark" content="分配角色" placement="top" :enterable='false'>
                        <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
                       </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <!-- size-change每页多少条 -->
            <!-- current-change 当前页-->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryObj.pagenum"
                :page-sizes="[1, 2, 5, 7]"
                :page-size="queryObj.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card> 
         <!--添加用户对话框  -->
         <!-- close窗口关闭的回调 -->
            <el-dialog
            title="添加用户"
            :visible.sync="isAddUser"
            width="50%"
            @close="addClose"
            >
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
            <el-form-item label="用户名称" prop="username">
                <el-input v-model="addForm.username"></el-input>
            </el-form-item>
            <el-form-item label="用户密码" prop="password">
                <el-input v-model="addForm.password"></el-input>
            </el-form-item>
             <el-form-item label="邮箱" prop="email">
                <el-input v-model="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
                <el-input v-model="addForm.mobile"></el-input>
            </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="isAddUser = false">取 消</el-button>
                <el-button type="primary" @click="addUserList">确 定</el-button>
            </span>
            </el-dialog>
            <!-- 修改用户对话框 -->
            <el-dialog
            title="提示"
            :visible.sync="isRevUser"
            width="50%"
            >
            <el-form :model="revForm" :rules="revFormRules" ref="revFormRef" label-width="100px">
            <el-form-item label="用户名">
                <el-input v-model="revForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="revForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
                <el-input v-model="revForm.mobile"></el-input>
            </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="isRevUser = false">取 消</el-button>
                <el-button type="primary" @click="revUserList">确 定</el-button>
            </span>
            </el-dialog>
            <!-- 分配角色对话框 -->
            <el-dialog
            title="分配角色"
            :visible.sync="showRole"
            width="30%">
            <p>当前用户 : {{roleList.username}}</p>
            <p>当前角色 : {{roleList.role_name}}</p>
            <!-- :value="item.id"这个值必须的唯一的 -->
            <p>分配角色 :   <el-select v-model="value" placeholder="请选择">
                               <el-option
                                v-for="item in newRoleList"
                                :key="item.id"
                                :label="item.roleName"
                                :value="item.id">
                                </el-option>
                            </el-select>
             </p>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showRole = false">取 消</el-button>
                <el-button type="primary" @click="setvalue">确 定</el-button>
            </span>
            </el-dialog>
    </div>
</template>

<script>
    export default {
    data () {
        return {
         //请求传过去的默认参数
           queryObj:{
               query:'',
               pagenum:1,
               pagesize:2
           },
           userList:[],
           total:0,
           //添加用户默认状态
           isAddUser:false,
           //添加表单
           addForm:{
              username:'',
              password:'',
              email:'',
              mobile:''
           },
        //    添加的验证规则
           addFormRules:{
              username:[
                  { required: true, message: '请输入用户名称', trigger: 'blur' },
                  { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
              ],
              password:[
                  { required: true, message: '请输入密码', trigger: 'blur' },
                  { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
              ],
              email:[
                     { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                     { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
              ],
              mobile:[
                  { required: true, message: '请输入手机号', trigger: 'blur' },
               
              ]                          
           },
        //    修改用户默认状态
           isRevUser:false,
           //修改用户表单数据
           revForm:{},
        //    修改的验证规则
           revFormRules:{
              email:[
                     { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                     { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
              ],
              mobile:[
                  { required: true, message: '请输入手机号', trigger: 'blur' },
               
              ]               
           },
           //分配角色对话框默认状态
           showRole:false,
           //需要分配角色的用户信息
           roleList:[],
           //分配新角色的数据
            newRoleList:[],
            //分配角色下拉菜单被选中的值
            value:''
        }
    },
    created () {
      this.getUserList()
    },
    methods:{
      async getUserList () {
           const res = await this.$http.get('users',{params:this.queryObj})
           if(res.data.meta.status==200){
             this.userList = res.data.data.users
             this.total = res.data.data.total
             console.log(this.userList)
           }else{
               return this.$message.error('获取列表失败');
           }
       },
       //每页多少条
       handleSizeChange (newPageSize) {
           console.log(newPageSize)
           this.queryObj.pagesize = newPageSize
           this.getUserList()
       },
        //当前页
       handleCurrentChange (newPageNum) {
           console.log(newPageNum)
           this.queryObj.pagenum = newPageNum
           this.getUserList()
       },
       //用户状态
      async userState (newState) {
         //两种方法
         //const res = await this.$http.put(`users/${newState.id}/state/${newState.mg_state}`)
         const res = await this.$http.put('users/'+newState.id+'/state/'+newState.mg_state)
        console.log(res)
          if(res.data.meta.status==200) {
            this.$message.success('更新状态成功');
          }else{
              newState.mg_state = !newState.mg_state
            return this.$message.error('更新状态失败');
          }
       },
       addUser () {
           this.isAddUser = !this.isAddUser
       },
       //添加窗口关闭清空类容
       addClose () {
          this.$refs.addFormRef.resetFields()
       },
       //点击添加按钮
       addUserList () {
          this.$refs.addFormRef.validate(async valid=>{
             if(!valid) {
                 return 
             }else {
                 const res = await this.$http.post('users',this.addForm)
                 if(res.data.meta.status == 201){
                   this.isAddUser = false
                   this.getUserList()
                   return this.$message.success('添加成功')
                 }
             }
          })   
       },
       //点击编辑按钮
      async revUser (data) {
         this.isRevUser = true  
         const res = await this.$http.get('users/'+data.id)
          if(res.data.meta.status == 200){
              this.revForm = res.data.data
              console.log(this.revForm)
          }else{
              return this.$message.error('获取用户失败');
          }
       },
    //  点击修改用户数据
       revUserList () {
         this.$refs.revFormRef.validate(async valid=>{
             if(!valid){
                return
             }else {
              const res = await this.$http.put('users/'+this.revForm.id,{
                  email:this.revForm.email,
                  mobile:this.revForm.mobile
              })
                if(res.data.meta.status == 200){
                    this.isRevUser = false
                    this.getUserList()
                    this.$message.success('修改成功')
                } else{
                    return this.$message.error('修改用户失败');
                }
             }
         })
       },
       //删除按钮
      async delUser (id) {
       const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        console.log(confirmResult)  //打印结果：点击确定confirm  点击取消是 cancel
        if(confirmResult == "cancel"){
             return this.$message.info('取消删除');
        }else{
            const res = await this.$http.delete('users/'+id)
            if(res.data.meta.status == 200){
              this.$message.success('删除成功')
              this.getUserList()
            }else{
                return this.$message.error('删除用户失败');
            }
        }
       },
       //分配角色
      async setRole (data) {
          this.roleList = data
          //获取所有角色列表
          const res = await this.$http.get('roles')
          if(res.data.meta.status == 200){
             this.newRoleList =res.data.data
             console.log(this.newRoleList)
          }else{
              return this.$message.error('获取分配角色失败');
          }
          this.showRole = true
       }, 
       //点击分配角色
      async setvalue () {
         if(!this.value){
           this.$message.info('请分配一个角色')
         }else{
             const res = await this.$http.put(`users/${this.roleList.id}/role`,{rid:this.value})
             if(res.data.meta.status == 200){
                this.$message.success('更新角色成功')
                this.getUserList()
                this.showRole = false
             }else{
                return this.$message.error('更新角色失败'); 
             }
         }
       }
    }
}

</script>

<style lang="less" scoped>

</style>